package net.qhzw.vip.qiyu.service;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayOrderQueryRequest;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.vip.qiyu.config.WxPayConfiguration;
import net.qhzw.vip.qiyu.entity.PayConfig;
import net.qhzw.vip.qiyu.handler.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class MyWxPayService {


    @Autowired
    private PayConfigService payConfigService;

    /**
     * 调用统一下单接口，并组装生成支付所需参数对象.
     *
     * @param request 统一下单请求参数
     * @return 返回 {@link com.github.binarywang.wxpay.bean.order}包下的类对象
     */
    public <T> T unifiedOrder(WxPayUnifiedOrderRequest request) {
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setSubMchId(request.getSubMchId());
        WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            if ("APP".equals(request.getTradeType())) {//trade_type=APP时
                PayConfig payConfig = payConfigService.getOne(Wrappers.<PayConfig>query().lambda()
                        .eq(PayConfig::getStatus, 1));
                request.setSubAppId(payConfig.getSubAppId());
            }
            if ("NATIVE".equals(request.getTradeType())) {//trade_type=NATIVE时
                request.setProductId(request.getOutTradeNo());
            }
            return wxPayService.createOrder(request);
        } catch (WxPayException e) {
            if ("INVALID_REQUEST".equals(e.getErrCode())) {
                throw new ApiException("订单号重复，请重新下单");
            }
            log.error("处理支付回调失败: {}" + JSON.toJSONString(e));
            throw new ApiException(e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }

    }

    /**
     * 处理支付回调
     *
     * @param xmlData
     * @return
     */
    public WxPayOrderNotifyResult notifyOrder(String xmlData) {
        log.info("处理支付回调: {}", JSON.toJSONString(xmlData));
        WxPayOrderNotifyResult rs = WxPayOrderNotifyResult.fromXML(xmlData);
//		String appId = rs.getAppid();
        String SubMchId = rs.getSubMchId();
        WxPayConfig wxPayConfig = new WxPayConfig();
//		wxPayConfig.setAppId(appId);
        wxPayConfig.setSubMchId(SubMchId);
        WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            log.info("处理支付回调成功: {}", JSON.toJSONString(notifyResult));
            return notifyResult;
        } catch (WxPayException e) {
            log.error("处理支付回调失败: {}" + JSON.toJSONString(e));
            throw new ApiException("" + e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }
    }

    /**
     * <pre>
     * 微信支付-申请退款.
     * 详见 https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4
     * 接口链接：https://api.mch.weixin.qq.com/secapi/pay/refund
     * @param request 请求对象
     * @return 退款操作结果 wx pay refund result
     * @throws WxPayException the wx pay exception
     */
    public WxPayRefundResult refundOrder(WxPayRefundRequest request) {
        log.info("申请退款: wxPayRefundRequest{}", JSON.toJSONString(request));
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(request.getAppid());
        wxPayConfig.setSubMchId(request.getSubMchId());
        com.github.binarywang.wxpay.service.WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            return wxPayService.refund(request);
        } catch (WxPayException e) {
            log.error("申请退款失败: {}" + JSON.toJSONString(e));
            throw new ApiException(e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }

    }

    /**
     * 处理退款回调
     *
     * @return
     */
    public WxPayRefundNotifyResult notifyRefunds(String xmlData) {
        log.info("处理退款回调: " + JSON.toJSONString(xmlData));
        WxPayOrderNotifyResult rs = WxPayOrderNotifyResult.fromXML(xmlData);
        String appId = rs.getAppid();
        String SubMchId = rs.getSubMchId();
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(appId);
        wxPayConfig.setSubMchId(SubMchId);
        com.github.binarywang.wxpay.service.WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            WxPayRefundNotifyResult notifyResult = wxPayService.parseRefundNotifyResult(xmlData);
            log.info("处理退款回调成功: " + JSON.toJSONString(notifyResult));
            return notifyResult;
        } catch (WxPayException e) {
            log.error("处理退款回调失败: {}" + JSON.toJSONString(e));
            throw new ApiException("处理退款回调失败:errMsg" + e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }
    }

    /**
     * 查询订单
     *
     * @param request
     * @return
     */
    public WxPayOrderQueryResult queryOrder(WxPayOrderQueryRequest request) {
        log.info("查询订单: wxPayOrderQueryRequest{}", JSON.toJSONString(request));
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(request.getAppid());
        wxPayConfig.setSubMchId(request.getSubMchId());
        com.github.binarywang.wxpay.service.WxPayService wxPayService = WxPayConfiguration.getPayService(wxPayConfig);
        try {
            WxPayOrderQueryResult wxPayOrderQueryResult = wxPayService.queryOrder(request);
            return wxPayOrderQueryResult;
        } catch (WxPayException e) {
            log.error("查询订单: errMsg {}", JSON.toJSONString(e));
            throw new ApiException(e.getReturnMsg() + "" + e.getCustomErrorMsg() + "" + e.getErrCodeDes());
        }
    }
}
